package com.wingtech.sheyifan.front;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXDialog;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * 2020-12-11 18:48 sheyifan Issue: init events on widgets
 */
public class Interactor {
    private StackPane root;

    public Interactor(StackPane root) {
        this.root = root;
    }

    /**
     * 2020-12-11 18:50 sheyifan Issue: connect all events with corresponding widgets
     */
    public void connectAll() {
        try {
            connectHelloDialog();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connectButton();
    }

    private void connectHelloDialog() throws IOException {
        // 2020-12-12 0:39 sheyifan Issue: connect events to HELLO dialog
        var helloDialog = (JFXDialog) root.lookup("#hello-dialog");
        var displayButton = (JFXButton) root.lookup("#display-hello-dialog-button");
        var continueButton = (JFXButton) root.lookup("#hello-dialog-continue-button");
        var rejectButton = (JFXButton) root.lookup("#hello-dialog-reject-button");
        // Dialog button event
        displayButton.setOnMouseClicked((mouseEvent) -> helloDialog.show(root));
        continueButton.setOnMouseClicked((mouseEvent) -> helloDialog.close());
        rejectButton.setOnAction(actionEvent -> {
            // Reject agreements, quit application
            helloDialog.close();
            Platform.exit();
        });

        // 2020-12-12 01:48 sheyifan Issue: read from data from file and fill them into HELLO dialog body
        var helloDialogBodyLabel = (Label) helloDialog.lookup("#hello-dialog-body-label");
        // 2020-12-23 13:53 sheyifan Issue: load resources in java, both works in .class and .jar (after deploy).
        // Attention: resource path start with leading forward slash ('/'), which means load resource from root
        // (namely ClassLoader). JDK 11 works.
        var helloDialogBodySourceStream = Interactor.class.getResourceAsStream("/com/wingtech/sheyifan/profile/hello-dialog-body.txt");
        var bufReader = new BufferedReader(new InputStreamReader(helloDialogBodySourceStream, StandardCharsets.UTF_8));
        // 2020-12-12 01:46 sheyifan Issue: stream api -- stream concatenate
        var lines = bufReader.lines().collect(Collectors.joining(System.lineSeparator()));
        helloDialogBodyLabel.setText(lines);
        bufReader.close();
    }

    private void connectButton() {

    }
}
